package cn.tedu.sp06zuul.cn.tedu.sp06zuul.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //设置过滤器的类型,pre,routing,post,error
    @Override
    public String filterType() {
//        return "pre";
        return FilterConstants.PRE_TYPE;
    }
    //设置过滤器的顺序号
    @Override
    public int filterOrder() {
        return 6;
    }
    //针对当前请求，是否要执行下面过滤代码
    @Override
    public boolean shouldFilter() {
        /*
        请求商品,需要判断权限;
        请求其他模块,跳过权限判断直接访问
         */
        //获取请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //从请求上下文对象获得 serviceId(正在调用的服务)
        String serviceId= (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        //serviceId是否是 tiem-service
        return "item-service".equals(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {

        RequestContext ctx = RequestContext.getCurrentContext();

        HttpServletRequest request = ctx.getRequest();

        String token = request.getParameter("token");

        if (StringUtils.isBlank(token)){
            ctx.setSendZuulResponse(false);
            //告诉客户端返回的数据是什么类型
            ctx.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8");
            String json = JsonResult.build().code(400).msg("未登录").toString();
            ctx.setResponseBody(json);
        }
        return null;//当前zuul版本中没有这个返回值，然后数据都是无效的
    }
}
